import axios from 'axios'
import router from '@/router'
import { getToken } from './modules/admin'
import * as user from './modules/user'
import * as supplier from './modules/supplier'
import * as processor from './modules/processor'
import * as product from './modules/product'
import * as productCategory from './modules/productCategory'
import * as productRecord from './modules/productRecord'
import * as processingBatch from './modules/processingBatch'
import * as qualityInspection from './modules/qualityInspection'
import * as statistics from './modules/statistics'
import * as admin from './modules/admin'
import qrcode from './modules/qrcode'
import feedback from './modules/feedback'
// 创建 axios 实例
const http = axios.create({
	baseURL: 'http://localhost:8080',
	timeout: 1000 * 30,
	withCredentials: true,
	headers: {
		'Content-Type': 'application/json; charset=utf-8'
	}
})

// 添加请求拦截器
http.interceptors.request.use(config => {
	// 在发送请求之前添加 token
	config.headers['token'] = getToken()
	return config
}, error => {
	return Promise.reject(error)
})

// 添加响应拦截器
http.interceptors.response.use(response => {
	if (response.data && response.data.code === 401) { // 401, token失效
		// 清除登录信息
		localStorage.removeItem('token')
		router.push({ name: 'Login' })
	}
	return response
}, error => {
	return Promise.reject(error)
})

// 注册所有的 API 模块
const api = {
	admin,
	user,
	supplier,
	processor,
	product,
	productCategory,
	productRecord,
	processingBatch,
	qualityInspection,
	statistics,
	qrcode,
	feedback
}

export default {
	...api,
	install(Vue) {
		Vue.prototype.$http = api
	}
}
